package me.chyxion.spring.ext.codegen.controllers;

import java.util.List;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import me.chyxion.spring.ext.codegen.services.CodeGenService;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.validator.constraints.NotBlank;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.alibaba.fastjson.JSONArray;
import static org.springframework.web.bind.annotation.RequestMethod.GET;
import static org.springframework.web.bind.annotation.RequestMethod.POST;
import static org.springframework.web.bind.annotation.RequestMethod.DELETE;

/**
 * @version 0.0.1
 * @since 0.0.1
 * @author Shaun Chyxion <br />
 * chyxion@163.com <br />
 * Oct 5, 2014 9:34:54 PM
 */
@Controller
@RequestMapping("/codegen")
public class CodeGenController {

	@Autowired
	private CodeGenService service;

	@RequestMapping(method = GET)
	public String index() {
        return "webapp/views/codegen";
	}

	@RequestMapping(method = POST)
	public void gen(@Valid GenForm form) {
		service.process(form.getModule(), form.getModel(), 
				form.getColumns(), form.getTable(), 
				form.isCreateTable());
	}

	@RequestMapping("/list")
	public List<?> list() {
		return service.list();
	}

	@RequestMapping(method = DELETE)
	public void delete(@RequestParam("items") JSONArray items, 
		@RequestParam(value = "dropTable", defaultValue = "true") 
		boolean dropTable) {
		service.delete(items, dropTable);
	}

	public static class GenForm {
		@NotNull
		private JSONArray columns;
		@NotBlank
		private String model;
		@NotBlank
		private String table;
		private String module;
		private boolean createTable = true;

		/**
		 * @return the columns
		 */
		public JSONArray getColumns() {
			return columns;
		}
		/**
		 * @param columns the columns to set
		 */
		public void setColumns(JSONArray columns) {
			this.columns = columns;
		}
		/**
		 * @return the model
		 */
		public String getModel() {
			return model;
		}
		/**
		 * @param model the model to set
		 */
		public void setModel(String model) {
			this.model = model;
		}
		/**
		 * @return the table
		 */
		public String getTable() {
			return table;
		}
		/**
		 * @param table the table to set
		 */
		public void setTable(String table) {
			this.table = table;
		}
		/**
		 * @return the module
		 */
		public String getModule() {
			return StringUtils.isNotBlank(module) ? module : "";
		}
		/**
		 * @param module the module to set
		 */
		public void setModule(String module) {
			this.module = module;
		}
		/**
		 * @return the createTable
		 */
		public boolean isCreateTable() {
			return createTable;
		}
		/**
		 * @param createTable the createTable to set
		 */
		public void setCreateTable(boolean createTable) {
			this.createTable = createTable;
		}
	}
}
